package com.zc.bigdata.yarn.v1;

import com.zc.bigdata.utils.IPParser;
import com.zc.bigdata.utils.LogParser;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * 省份访问统计
 */
public class PageAPP {

    public static void main(String[] args) throws Exception {
        System.setProperty("hadoop.home.dir", "D://gitee//hadoop-2.6.0");
        Configuration configuration = new Configuration();
        Job job = Job.getInstance(configuration);

        job.setJarByClass(PageAPP.class);
        job.setMapperClass(MyMapper.class);
        job.setReducerClass(MyReducer.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        // 提前删除输入目录，以免运行报错
        FileUtils.deleteDirectory(new File("output//tracklog//page"));

        // 设置输入文件夹和输出文件夹
        FileInputFormat.setInputPaths(job, new Path("input//tracklog//"));
        FileOutputFormat.setOutputPath(job, new Path("output//tracklog//page"));

        // 执行job
        boolean result = job.waitForCompletion(true);
        System.out.println(result);

    }

    static class MyMapper extends Mapper<LongWritable, Text, Text, LongWritable> {

        private LongWritable ONE = new LongWritable(1);

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            Map<String, String> resultMap = LogParser.parseLog(value.toString());
            String pageId = LogParser.getPageId(resultMap.get("url"));
            if(StringUtils.isBlank(pageId)){
                pageId = "-";
            }
            context.write(new Text(pageId), ONE);
        }
    }

    static class MyReducer extends Reducer<Text, LongWritable, Text, LongWritable> {
        @Override
        protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
            long sum = 0L;
            for (LongWritable value : values) {
                sum += value.get();
            }
            context.write(key, new LongWritable(sum));
        }
    }

}
